package com.hbnu.gui.util;

import com.hbnu.gui.constant.Views;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class WindowManager {
    private static final Logger logger = LoggerFactory.getLogger(WindowManager.class);
    private static WindowManager instance;
    private final Map<Views, Stage> stageCache;
    private Stage primaryStage;

    private WindowManager() {
        stageCache = new HashMap<>();
    }

    public static synchronized WindowManager getInstance() {
        if (instance == null) {
            instance = new WindowManager();
        }
        return instance;
    }

    public void setPrimaryView(Views primaryView) {
        if (primaryStage != null) {
            logger.warn("主窗口已设置，请勿重复调用。");
            return;
        }

        try {
            Stage stage = new Stage();
            stage.initStyle(StageStyle.TRANSPARENT);

            Views.ViewLoadResult loadResult = primaryView.load();
            stage.setScene(new Scene(loadResult.getRoot()));

            stageCache.put(primaryView, stage);
            primaryStage = stage;
        } catch (IOException e) {
            logger.error("初始化主窗口 '{}' 失败！", primaryView.getDesc(), e);
            AlertUtil.showAlert(Alert.AlertType.ERROR, "严重错误", "加载主界面失败，应用可能无法正常运行。");
        }
    }

    public void showView(Views view) {
        try {
            Stage stage = stageCache.get(view);
            boolean isNewStage = false;

            if (stage == null) {
                stage = new Stage();
                stage.initStyle(StageStyle.TRANSPARENT);

                if (primaryStage != null) {
                    stage.initOwner(primaryStage);
                }
                isNewStage = true;
            }

            Views.ViewLoadResult loadResult = view.load();
            stage.setScene(new Scene(loadResult.getRoot()));

            if (view.isCacheable() && isNewStage) {
                stageCache.put(view, stage);
            }
            stage.show();
        } catch (IOException e) {
            logger.error("显示视图异常: ", e);
        }
    }

    public void closeView(Views view) {
        Stage stage = stageCache.get(view);
        if (stage != null && stage.isShowing()) {
            stage.close();

            if (stage == primaryStage) {
                logger.info("主窗口 '{}' 已关闭，应用将退出。", view.getDesc());
                System.exit(0);
            }
        } else if (stage == null) {
            logger.warn("视图 '{}' 未找到，应用将退出。", view.getDesc());
            System.exit(0);
        } else {
            logger.warn("视图 '{}' 不在运行状态...", view.getDesc());
        }
    }

    public void exitApplication() {
        if (primaryStage != null && primaryStage.isShowing()) {
            primaryStage.close();
        } else {
            logger.warn("主窗口未找到或未显示，将强制退出应用。");
            System.exit(0);
        }
    }

    public Stage getPrimaryStage() {
        return primaryStage;
    }

    public void setPrimaryStage(Stage primaryStage) {
        this.primaryStage = primaryStage;
    }

    public Optional<Views> getPrimaryViewEnum() {
        if (primaryStage == null) {
            return Optional.empty();
        }

        return stageCache.entrySet().stream()
                .filter(entry -> entry.getValue().equals(primaryStage))
                .map(Map.Entry::getKey)
                .findFirst();
    }
}
